package com.learn.set;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class SetTest {

    public static void main(String[] args) {
        TreeSet set = new TreeSet();

        set.add(new User("Tom", 23));
        set.add(new User("Jerry", 26));
        set.add(new User("Eric", 24));
        set.add(new User("Jerry", 33));
        set.add(new User("Jeff", 33));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        System.out.println("**********************");

        Comparator comparator = new Comparator(){
            //按年龄从小到大排序
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(), u2.getAge());
                }else {
                    throw new RuntimeException("输入类型不一致");
                }
            }
        };

        TreeSet set1 = new TreeSet(comparator);
        set1.addAll(set);
        Iterator iterator1 = set1.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
    }

}
